{% extends "base.html" %}

{% block title %}插件管理{% endblock %}

{% block content %}
<div class="space-y-6">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center">
        <div>
            <h1 class="text-3xl font-bold text-gray-900">
                <i class="fas fa-plug mr-3 text-blue-500"></i>插件管理
            </h1>
            <p class="text-gray-600 mt-2">管理和配置系统中的所有插件</p>
        </div>
        <div class="flex space-x-3">
            <button onclick="refreshPlugins()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-colors">
                <i class="fas fa-sync-alt mr-2"></i>刷新
            </button>
            <button onclick="showUploadModal()" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg transition-colors">
                <i class="fas fa-upload mr-2"></i>上传插件
            </button>
        </div>
    </div>

    <!-- 统计信息 -->
    <div class="grid md:grid-cols-4 gap-4">
        <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-blue-100 text-blue-500">
                    <i class="fas fa-plug text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">总插件数</p>
                    <p class="text-2xl font-semibold text-gray-900" id="total-plugins">0</p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-green-100 text-green-500">
                    <i class="fas fa-play text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">运行中</p>
                    <p class="text-2xl font-semibold text-gray-900" id="active-plugins">0</p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-yellow-100 text-yellow-500">
                    <i class="fas fa-pause text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">已加载</p>
                    <p class="text-2xl font-semibold text-gray-900" id="loaded-plugins">0</p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-red-100 text-red-500">
                    <i class="fas fa-exclamation-triangle text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">错误</p>
                    <p class="text-2xl font-semibold text-gray-900" id="error-plugins">0</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 插件列表 -->
    <div class="bg-white rounded-lg shadow-md">
        <div class="px-6 py-4 border-b border-gray-200">
            <h2 class="text-lg font-semibold text-gray-900">插件列表</h2>
        </div>
        
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">插件</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">版本</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">作者</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200" id="plugins-table-body">
                    <!-- 插件列表将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 插件详情模态框 -->
<div id="plugin-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-medium text-gray-900" id="modal-title">插件详情</h3>
                <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div id="modal-content">
                <!-- 模态框内容将通过JavaScript动态加载 -->
            </div>
        </div>
    </div>
</div>

<!-- 上传插件模态框 -->
<div id="upload-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-1/2 shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-medium text-gray-900">上传插件</h3>
                <button onclick="closeUploadModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">选择插件文件</label>
                    <input type="file" id="plugin-file" accept=".py" class="w-full p-2 border border-gray-300 rounded-md">
                </div>
                <div class="flex justify-end space-x-3">
                    <button onclick="closeUploadModal()" class="px-4 py-2 text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50">
                        取消
                    </button>
                    <button onclick="uploadPlugin()" class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600">
                        上传
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    let plugins = [];

    // 页面加载时获取插件列表
    document.addEventListener('DOMContentLoaded', function() {
        loadPlugins();
    });

    async function loadPlugins() {
        try {
            const response = await axios.get(API_BASE);
            plugins = response.data;
            updatePluginsTable();
            updateStatistics();
        } catch (error) {
            showNotification('加载插件列表失败', 'error');
            console.error('Error loading plugins:', error);
        }
    }

    function updatePluginsTable() {
        const tbody = document.getElementById('plugins-table-body');
        tbody.innerHTML = '';

        plugins.forEach(plugin => {
            const row = document.createElement('tr');
            row.className = 'hover:bg-gray-50';
            
            const statusBadge = getStatusBadge(plugin.status);
            const tags = plugin.info.tags.map(tag => 
                `<span class="inline-block bg-gray-200 rounded-full px-2 py-1 text-xs font-semibold text-gray-700 mr-1">${tag}</span>`
            ).join('');

            row.innerHTML = `
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 h-10 w-10">
                            <div class="h-10 w-10 rounded-full bg-blue-100 flex items-center justify-center">
                                <i class="fas fa-puzzle-piece text-blue-500"></i>
                            </div>
                        </div>
                        <div class="ml-4">
                            <div class="text-sm font-medium text-gray-900">${plugin.info.name}</div>
                            <div class="text-sm text-gray-500">${plugin.info.description}</div>
                            <div class="mt-1">${tags}</div>
                        </div>
                    </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    ${statusBadge}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    ${plugin.info.version}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    ${plugin.info.author}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div class="flex space-x-2">
                        ${plugin.status.active ? 
                            `<button onclick="stopPlugin('${plugin.name}')" class="text-red-600 hover:text-red-900">
                                <i class="fas fa-stop"></i>
                            </button>` :
                            `<button onclick="startPlugin('${plugin.name}')" class="text-green-600 hover:text-green-900">
                                <i class="fas fa-play"></i>
                            </button>`
                        }
                        <button onclick="showPluginDetails('${plugin.name}')" class="text-blue-600 hover:text-blue-900">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button onclick="reloadPlugin('${plugin.name}')" class="text-yellow-600 hover:text-yellow-900">
                            <i class="fas fa-sync-alt"></i>
                        </button>
                        <button onclick="unloadPlugin('${plugin.name}')" class="text-red-600 hover:text-red-900">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            `;
            
            tbody.appendChild(row);
        });
    }

    function updateStatistics() {
        const total = plugins.length;
        const active = plugins.filter(p => p.status.active).length;
        const loaded = plugins.filter(p => p.status.loaded).length;
        const errors = plugins.filter(p => !p.status.loaded && !p.status.active).length;

        document.getElementById('total-plugins').textContent = total;
        document.getElementById('active-plugins').textContent = active;
        document.getElementById('loaded-plugins').textContent = loaded;
        document.getElementById('error-plugins').textContent = errors;
    }

    async function startPlugin(pluginName) {
        try {
            await axios.post(`${API_BASE}/${pluginName}/start`);
            showNotification(`插件 ${pluginName} 启动成功`, 'success');
            await loadPlugins();
        } catch (error) {
            showNotification(`启动插件 ${pluginName} 失败`, 'error');
        }
    }

    async function stopPlugin(pluginName) {
        try {
            await axios.post(`${API_BASE}/${pluginName}/stop`);
            showNotification(`插件 ${pluginName} 停止成功`, 'success');
            await loadPlugins();
        } catch (error) {
            showNotification(`停止插件 ${pluginName} 失败`, 'error');
        }
    }

    async function reloadPlugin(pluginName) {
        try {
            await axios.post(`${API_BASE}/${pluginName}/reload`);
            showNotification(`插件 ${pluginName} 重新加载成功`, 'success');
            await loadPlugins();
        } catch (error) {
            showNotification(`重新加载插件 ${pluginName} 失败`, 'error');
        }
    }

    async function unloadPlugin(pluginName) {
        if (!confirm(`确定要卸载插件 ${pluginName} 吗？`)) {
            return;
        }
        
        try {
            await axios.delete(`${API_BASE}/${pluginName}`);
            showNotification(`插件 ${pluginName} 卸载成功`, 'success');
            await loadPlugins();
        } catch (error) {
            showNotification(`卸载插件 ${pluginName} 失败`, 'error');
        }
    }

    async function showPluginDetails(pluginName) {
        try {
            const response = await axios.get(`${API_BASE}/${pluginName}`);
            const plugin = response.data;
            
            document.getElementById('modal-title').textContent = `插件详情 - ${plugin.info.name}`;
            
            const content = `
                <div class="space-y-4">
                    <div class="grid md:grid-cols-2 gap-4">
                        <div>
                            <h4 class="font-semibold text-gray-900 mb-2">基本信息</h4>
                            <dl class="space-y-1">
                                <dt class="text-sm font-medium text-gray-500">名称</dt>
                                <dd class="text-sm text-gray-900">${plugin.info.name}</dd>
                                <dt class="text-sm font-medium text-gray-500">版本</dt>
                                <dd class="text-sm text-gray-900">${plugin.info.version}</dd>
                                <dt class="text-sm font-medium text-gray-500">作者</dt>
                                <dd class="text-sm text-gray-900">${plugin.info.author}</dd>
                                <dt class="text-sm font-medium text-gray-500">描述</dt>
                                <dd class="text-sm text-gray-900">${plugin.info.description}</dd>
                            </dl>
                        </div>
                        <div>
                            <h4 class="font-semibold text-gray-900 mb-2">状态信息</h4>
                            <dl class="space-y-1">
                                <dt class="text-sm font-medium text-gray-500">加载状态</dt>
                                <dd class="text-sm text-gray-900">${plugin.status.loaded ? '已加载' : '未加载'}</dd>
                                <dt class="text-sm font-medium text-gray-500">运行状态</dt>
                                <dd class="text-sm text-gray-900">${plugin.status.active ? '运行中' : '已停止'}</dd>
                                <dt class="text-sm font-medium text-gray-500">创建时间</dt>
                                <dd class="text-sm text-gray-900">${formatDate(plugin.info.created_at)}</dd>
                                <dt class="text-sm font-medium text-gray-500">更新时间</dt>
                                <dd class="text-sm text-gray-900">${formatDate(plugin.info.updated_at)}</dd>
                            </dl>
                        </div>
                    </div>
                    
                    <div>
                        <h4 class="font-semibold text-gray-900 mb-2">标签</h4>
                        <div class="flex flex-wrap gap-2">
                            ${plugin.info.tags.map(tag => 
                                `<span class="bg-blue-100 text-blue-800 text-xs font-medium px-2.5 py-0.5 rounded">${tag}</span>`
                            ).join('')}
                        </div>
                    </div>
                    
                    <div>
                        <h4 class="font-semibold text-gray-900 mb-2">配置</h4>
                        <pre class="bg-gray-100 p-3 rounded text-sm overflow-x-auto">${JSON.stringify(plugin.config, null, 2)}</pre>
                    </div>
                </div>
            `;
            
            document.getElementById('modal-content').innerHTML = content;
            document.getElementById('plugin-modal').classList.remove('hidden');
        } catch (error) {
            showNotification('获取插件详情失败', 'error');
        }
    }

    function closeModal() {
        document.getElementById('plugin-modal').classList.add('hidden');
    }

    function showUploadModal() {
        document.getElementById('upload-modal').classList.remove('hidden');
    }

    function closeUploadModal() {
        document.getElementById('upload-modal').classList.add('hidden');
    }

    async function uploadPlugin() {
        const fileInput = document.getElementById('plugin-file');
        const file = fileInput.files[0];
        
        if (!file) {
            showNotification('请选择插件文件', 'warning');
            return;
        }
        
        // 这里应该实现文件上传逻辑
        showNotification('插件上传功能待实现', 'info');
        closeUploadModal();
    }

    function refreshPlugins() {
        loadPlugins();
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('plugin-modal');
        const uploadModal = document.getElementById('upload-modal');
        
        if (event.target === modal) {
            closeModal();
        }
        if (event.target === uploadModal) {
            closeUploadModal();
        }
    }
</script>
{% endblock %} 